# -*- coding: utf-8 -*-
import sys
import requests
import random
from PySide import QtGui
from PySide import QtCore


class QuerySignal(QtCore.QObject):
    query = QtCore.Signal()


class ListBox(QtGui.QWidget):
    def __init__(self, parent=None):
        super(ListBox, self).__init__()

        self.setWindowTitle(u'查询结果')
        self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowStaysOnTopHint)
        self.setMinimumWidth(800)
        self.table = QtGui.QListWidget()

        main = QtGui.QVBoxLayout()
        main.addWidget(self.table)
        self.setLayout(main)

    def setData(self, data):
        self.table.clear()
        self.table.addItems(map(lambda x: x['time']+'\t'+x['context'], data))


class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__()

        self.setWindowTitle(u'快递查询')
        self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowStaysOnTopHint)

        self.code = QtGui.QLineEdit(u'')
        self.code.setPlaceholderText(u'输入快递单号')
        self.button = QtGui.QPushButton(u'查询')
        self.button.clicked.connect(self.click)
        self.box = ListBox()

        self.query = QuerySignal()
        self.query.query.connect(self.run)

        main = QtGui.QVBoxLayout()
        main.addWidget(self.code)
        main.addWidget(self.button)
        self.setLayout(main)

    def kd_query(self, code):
        # 通过快递号获取快递基本信息
        r = requests.get(
            url='http://www.kuaidi100.com/autonumber/autoComNum',
            params={'text': code})
        possiblyres = r.json()
        if 'auto' not in possiblyres:
            return None
        possibly = possiblyres['auto']

        # 遍历可能性
        for e in possibly:
            r = requests.get(
                url='http://www.kuaidi100.com/query',
                params={
                    'type': e['comCode'],
                    'postid': code,
                    'id': 1,
                    'valicode': '',
                    'temp': random.random()})
            res = r.json()
            if res['message'] == 'ok':
                return res['data']

    def run(self):
        code = self.code.text().strip()
        res = self.kd_query(code)
        if not res:
            QtGui.QMessageBox.information(self, u'结果', u'查无此快递')
            return
        # Example: 500366970675 adsfd
        self.box.setData(res)
        self.box.show()

    def click(self):
        self.query.query.emit()


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    widget = Window()
    widget.show()
    sys.exit(app.exec_())
